package net.chrisrichardson.ec2deployer.applications;

import org.apache.commons.logging.LogFactory
import org.apache.commons.logging.Log
import net.chrisrichardson.ec2deployer.core.S3Synchronizer
import net.chrisrichardson.ec2deployer.core.AWSProperties
import net.chrisrichardson.ec2deployer.core.AwsUtilities;

/**
 Represents a web application.
 Caches the web application in an S3 bucket in order to avoid slow uploads
 */

public class WebApp {

    private Log logger = LogFactory.getLog(getClass())

    String explodedWar
    String context

    WebApp() {}
    
    public WebApp(String pathToExplodedWar, String context) {
        this.explodedWar = pathToExplodedWar
        this.context = context
    }

    String getS3Bucket() {
        if (explodedWar.startsWith("s3://")) {
            int prefixLength = "s3://".length()
            int n = explodedWar.indexOf('/', prefixLength)
            if (n >= 0)
                return explodedWar.substring(prefixLength, n)
            else
                return explodedWar.substring(prefixLength)
        } else
            return context + "-tmp-war"
    }

    /**
     Upload the application to an S3 bucket
     */
    public uploadToS3(AWSProperties awsProperties, String bucketPrefix) {
        if (!explodedWar.startsWith("s3://")) {
            logger.info("Uploading war $context to S3")
            S3Synchronizer s3Synchronizer = new S3Synchronizer(awsProperties)
            s3Synchronizer.uploadToS3([explodedWar], bucketPrefix, s3Bucket)
        } else
            logger.info("Using war in bucket: $explodedWar")
    }

    /**
     Deploys the application in the TomcatServer's webapp directory
     */
    public void updateTomcat(ApplicationServer server, String bucketPrefix) {
        assert explodedWar
        updateWar(server, bucketPrefix)
    }

    private void  updateWar(ApplicationServer server, String bucketPrefix) {
        def host = server.host
        if (explodedWar.endsWith(".war")) {
            AwsUtilities awsUtilities = new AwsUtilities(host)
            awsUtilities.s3get "${s3Bucket}${subDirectory}",  "${server.deploymentDirectory}/${context}.war"
        } else  {
            S3Synchronizer s3Synchronizer = new S3Synchronizer(host.awsProperties)
            s3Synchronizer.downloadFromS3(host, bucketPrefix, s3Bucket, "/tmp/$s3Bucket")
            if (server.supportsExplodedWars())
                host.ssh("rsync --del -u -v -r  /tmp/${s3Bucket}${subDirectory}/ ${server.deploymentDirectory}/$context")
            else
                host.ssh("cd /tmp/${s3Bucket}${subDirectory}; jar cf /tmp/${context}.war . ; cp /tmp/${context}.war ${server.deploymentDirectory}")
        }
    }

    String getSubDirectory() {
        if (explodedWar.startsWith("s3://")) {
            int prefixLength = "s3://".length()
            int n = explodedWar.indexOf('/', prefixLength)
            if (n >= 0)
                return explodedWar.substring(n)
            else
                return ""
        } else {
            int n = Math.max(explodedWar.lastIndexOf('/'), explodedWar.lastIndexOf('\\'))
            if (n >= 0)
                return "/" + explodedWar.substring(n + 1)
            else
                return "/" + explodedWar
        }
    }

    String getActualContext() {
        "ROOT".equals(context) ? "" : context
    }

}